package cn.org.donald;

import org.apache.http.conn.ssl.DefaultHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.KeyStore;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Donald
 * @since 2023-08-18 18:39:55
 **/
public class Application {
    public static void main(String[] args) throws Exception {
        HttpComponentsClientHttpRequestFactory httpComponentsClientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(initSSLConfig());
        RestTemplate restTemplate = new RestTemplate(httpComponentsClientHttpRequestFactory);
        Map<String, String> map = new HashMap<>();
        map.put("key", "value");
        ResponseEntity<String> stringResponseEntity = restTemplate.postForEntity("https://192.168.0.73:20100/license-onstage-api/test/do-test", map, String.class);
        System.out.println(stringResponseEntity.getBody());
    }

    private static final String KEY_STORE_URL = "C:\\Users\\xie71\\Downloads\\keystore-client.p12";
    private static final String KEY_STORE_PASSWORD = "123456";
    private static final String TRUST_STORE_URL = "C:\\Users\\xie71\\Downloads\\truststore.p12";
    private static final String TRUST_STORE_PASSWORD = "123456";

    
    private static CloseableHttpClient initSSLConfig() throws Exception {
        // 加载自己的证书
        KeyStore selfStore = KeyStore.getInstance("pkcs12");
        selfStore.load(Files.newInputStream(Paths.get(KEY_STORE_URL)), KEY_STORE_PASSWORD.toCharArray());
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(selfStore, KEY_STORE_PASSWORD.toCharArray());

        // 加载服务端证书信任库
        KeyStore trustStore = KeyStore.getInstance("pkcs12");
        trustStore.load(Files.newInputStream(Paths.get(TRUST_STORE_URL)), TRUST_STORE_PASSWORD.toCharArray());
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(trustStore);

        SSLContext tls = SSLContext.getInstance("TLS");
        tls.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

        SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(tls, new DefaultHostnameVerifier());
        return HttpClients.custom().setSSLSocketFactory(sslConnectionSocketFactory).build();
    }
}
